package cn.zhentao.controller;

import cn.zhentao.common.Result;
import cn.zhentao.entity.AiSession;
import cn.zhentao.service.AiSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * AI会话管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/ai/session")
@CrossOrigin(origins = "*")
public class AiSessionController {
    
    @Autowired
    private AiSessionService aiSessionService;
    
    /**
     * 获取AI会话信息
     */
    @GetMapping("/{userId}/{featureType}")
    public Result<Map<String, Object>> getAiSession(@PathVariable Long userId, @PathVariable String featureType) {
        try {
            AiSession.AiFeatureType type = AiSession.AiFeatureType.valueOf(featureType.toUpperCase());
            AiSession aiSession = aiSessionService.getOrCreateAiSession(userId, type);
            
            Map<String, Object> result = buildSessionInfo(aiSession);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取AI会话异常: {}", e.getMessage(), e);
            return Result.error("获取AI会话失败: " + e.getMessage());
        }
    }
    
    /**
     * 重置AI会话
     */
    @PostMapping("/reset")
    public Result<Map<String, Object>> resetAiSession(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String featureType = request.get("featureType").toString();
            
            AiSession.AiFeatureType type = AiSession.AiFeatureType.valueOf(featureType.toUpperCase());
            
            // 删除旧会话，创建新会话
            AiSession oldSession = aiSessionService.getOrCreateAiSession(userId, type);
            aiSessionService.removeSession(oldSession.getSessionId());
            
            AiSession newSession = aiSessionService.createAiSession(userId, type);
            Map<String, Object> result = buildSessionInfo(newSession);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("重置AI会话异常: {}", e.getMessage(), e);
            return Result.error("重置AI会话失败: " + e.getMessage());
        }
    }
    
    /**
     * 设置用户偏好
     */
    @PostMapping("/preference")
    public Result<String> setUserPreference(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String featureType = request.get("featureType").toString();
            String key = request.get("key").toString();
            Object value = request.get("value");
            
            AiSession.AiFeatureType type = AiSession.AiFeatureType.valueOf(featureType.toUpperCase());
            AiSession aiSession = aiSessionService.getOrCreateAiSession(userId, type);
            
            aiSessionService.setUserPreference(aiSession.getSessionId(), key, value);
            
            return Result.success("偏好设置成功");
        } catch (Exception e) {
            log.error("设置用户偏好异常: {}", e.getMessage(), e);
            return Result.error("设置偏好失败: " + e.getMessage());
        }
    }
    
    /**
     * 设置上下文数据
     */
    @PostMapping("/context")
    public Result<String> setContextData(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String featureType = request.get("featureType").toString();
            String key = request.get("key").toString();
            Object value = request.get("value");
            
            AiSession.AiFeatureType type = AiSession.AiFeatureType.valueOf(featureType.toUpperCase());
            AiSession aiSession = aiSessionService.getOrCreateAiSession(userId, type);
            
            aiSessionService.setContextData(aiSession.getSessionId(), key, value);
            
            return Result.success("上下文设置成功");
        } catch (Exception e) {
            log.error("设置上下文数据异常: {}", e.getMessage(), e);
            return Result.error("设置上下文失败: " + e.getMessage());
        }
    }
    
    /**
     * 暂停会话
     */
    @PostMapping("/pause")
    public Result<String> pauseSession(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String featureType = request.get("featureType").toString();
            
            AiSession.AiFeatureType type = AiSession.AiFeatureType.valueOf(featureType.toUpperCase());
            AiSession aiSession = aiSessionService.getOrCreateAiSession(userId, type);
            
            aiSessionService.pauseSession(aiSession.getSessionId());
            
            return Result.success("会话已暂停");
        } catch (Exception e) {
            log.error("暂停会话异常: {}", e.getMessage(), e);
            return Result.error("暂停会话失败: " + e.getMessage());
        }
    }
    
    /**
     * 恢复会话
     */
    @PostMapping("/resume")
    public Result<String> resumeSession(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String featureType = request.get("featureType").toString();
            
            AiSession.AiFeatureType type = AiSession.AiFeatureType.valueOf(featureType.toUpperCase());
            AiSession aiSession = aiSessionService.getOrCreateAiSession(userId, type);
            
            aiSessionService.resumeSession(aiSession.getSessionId());
            
            return Result.success("会话已恢复");
        } catch (Exception e) {
            log.error("恢复会话异常: {}", e.getMessage(), e);
            return Result.error("恢复会话失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取会话历史
     */
    @GetMapping("/history/{userId}/{featureType}")
    public Result<Map<String, Object>> getSessionHistory(@PathVariable Long userId, @PathVariable String featureType,
                                                        @RequestParam(defaultValue = "10") Integer count) {
        try {
            AiSession.AiFeatureType type = AiSession.AiFeatureType.valueOf(featureType.toUpperCase());
            AiSession aiSession = aiSessionService.getOrCreateAiSession(userId, type);
            
            Map<String, Object> result = new HashMap<>();
            result.put("sessionId", aiSession.getSessionId());
            result.put("featureType", aiSession.getFeatureType());
            result.put("conversationHistory", aiSession.getRecentHistory(count));
            result.put("totalInteractions", aiSession.getSessionStats().getTotalInteractions());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取会话历史异常: {}", e.getMessage(), e);
            return Result.error("获取历史失败: " + e.getMessage());
        }
    }
    
    /**
     * 构建会话信息
     */
    private Map<String, Object> buildSessionInfo(AiSession aiSession) {
        Map<String, Object> sessionInfo = new HashMap<>();
        sessionInfo.put("sessionId", aiSession.getSessionId());
        sessionInfo.put("featureType", aiSession.getFeatureType().name());
        sessionInfo.put("sessionState", aiSession.getSessionState().name());
        sessionInfo.put("createTime", aiSession.getCreateTime());
        sessionInfo.put("updateTime", aiSession.getUpdateTime());
        
        // 用户偏好信息
        Map<String, Object> preferences = new HashMap<>();
        preferences.put("language", aiSession.getUserPreferences().getLanguage());
        preferences.put("responseStyle", aiSession.getUserPreferences().getResponseStyle());
        preferences.put("maxHistoryLength", aiSession.getUserPreferences().getMaxHistoryLength());
        preferences.put("enablePersonalization", aiSession.getUserPreferences().getEnablePersonalization());
        preferences.put("customSettings", aiSession.getUserPreferences().getCustomSettings());
        sessionInfo.put("preferences", preferences);
        
        // 会话统计
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalInteractions", aiSession.getSessionStats().getTotalInteractions());
        stats.put("totalTokensUsed", aiSession.getSessionStats().getTotalTokensUsed());
        stats.put("averageResponseTime", aiSession.getSessionStats().getAverageResponseTime());
        stats.put("lastActiveTime", aiSession.getSessionStats().getLastActiveTime());
        sessionInfo.put("stats", stats);
        
        // 上下文数据
        sessionInfo.put("contextData", aiSession.getContextData());
        
        return sessionInfo;
    }
}
